package com.pan.download3.ctrl;

import com.pan.entity.Chapter;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 这个是用来控制爬取任务发放的
 */
public class TaskCtrl {
    private List<Chapter> workList;

    ReentrantLock reentrantLock = new ReentrantLock();

    public TaskCtrl(List<Chapter> workList,boolean sort) {
        if (sort) {
            this.workList = workList.stream().sorted((o1, o2) -> {
                if (o1.getOrderNumber() > o2.getOrderNumber()) return 1;
                else if (o1.getOrderNumber() == o2.getOrderNumber()) throw new RuntimeException("有章节序号有相同的");
                return -1;
            }).collect(Collectors.toList());
        }
        else {
            this.workList = workList;
        }
    }

    public TaskCtrl(List<Chapter> workList){
        this(workList,false);
    }


    public Chapter getTask(){
        Chapter chapter;
        reentrantLock.lock();
//        这个看情况，有些网址访问太快会栏，可以设置任务发放速度
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (workList.size()==0){
            reentrantLock.unlock();
            return null;
        }
        chapter = workList.get(0);
        workList.remove(0);
        reentrantLock.unlock();
        return chapter;
    }

    public boolean cancelTask (Chapter chapter){
        reentrantLock.lock();
        for (int i = 0; i < workList.size(); i++) {
            if (chapter.getOrderNumber()<workList.get(i).getOrderNumber()){
                workList.add(i,chapter);
                reentrantLock.unlock();
                return true;
            }
        }
        reentrantLock.unlock();
        return false;
    }

}
